package com.lqk.selector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SelectorDemo1 {
    public static void main(String[] args) throws Exception {
        // 创建 Selector
        Selector selector = Selector.open();

        // 创建 Channel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        // 设置为非阻塞模式 (与Selector一起使用时，Channel必须处于非阻塞模式下)
        serverSocketChannel.configureBlocking(false);

        // 绑定连接
        serverSocketChannel.bind(new InetSocketAddress(9999));


        //将通道注册到选择器上，定制监听事件为“接收”事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 查询已经就绪通道操作
        Set<SelectionKey> selectionKeys = selector.selectedKeys();

        // 遍历集合
        Iterator<SelectionKey> iterator = selectionKeys.iterator();
        while (iterator.hasNext()){
            SelectionKey key = iterator.next();
            // 判断key就绪状态操作
            if (key.isAcceptable()){

            }else if (key.isConnectable()){

            }else if (key.isReadable()){

            }else if (key.isWritable()){

            }
            iterator.remove();
        }

    }
}
